import { legacyLogicalPropertiesTransformer, StyleProvider } from '@ant-design/cssinjs';
import { ConfigProvider } from 'antd';
import zh_CN from 'antd/locale/zh_CN';
import React, { Suspense, useEffect } from 'react';
import { HashRouter, Navigate, Route, Routes, useLocation } from 'react-router';
import { ErrorViewer } from './component/ErrorViewer';
import { RouteGuard } from './component/RouteGuard';
import { GlobalValue } from './GlobalValue';
import Devices from './hooks/Devices';
import { Notificatorio, Toast } from './hooks/Providers';
import { SmallScreen } from './hooks/SmallScreen';
import { Theme } from './hooks/theme';
import { Paths } from './paths';

function Fallback() {
  console.error(`尝试访问${location.pathname}, 但没有找到对应的路由关系，请检查Paths.Relations`)
  return <Navigate to={Paths.All.Main} replace />
}

export default function App(): React.ReactElement {
  const appRef = React.useRef<HTMLDivElement>(null);
  const { theme } = Theme.use({ is_root: true });
  const routes = Paths.Relations[Paths.All.Root]?.map(RouteGuard.Route);
  const smallScreen = SmallScreen.use()
  const [, setGlobalValue] = GlobalValue.use()

  useEffect(() => setGlobalValue('smallScreen', smallScreen), [smallScreen])
  return (
    <Devices.Provider>
      <ConfigProvider locale={zh_CN} theme={theme} getPopupContainer={() => appRef.current!}>
        <StyleProvider hashPriority="high" transformers={[legacyLogicalPropertiesTransformer]}>
          <Toast.Provider>
            <Notificatorio.Provider>
              <HashRouter>
                <Routes>
                  {routes}
                  <Route path="*" element={<Fallback />} />
                </Routes>
              </HashRouter>
              <ErrorViewer.Component />
            </Notificatorio.Provider>
          </Toast.Provider>
        </StyleProvider>
      </ConfigProvider>
    </Devices.Provider>
  )
}
